<?php

namespace s94\wechat;

/**
 * 图文草稿管理
 */
class Article extends Base
{
    public $articleList = [];

    /**添加一个文章到 $articleList 中，便于调用 add 方法
     * @param string $title 标题，必填
     * @param string $thumb_media_id 封面图片素材，必须是永久MediaID，必填
     * @param string $content 图文内容，支持HTML(不能有JS)，涉及图片url必须来源 "上传图文消息内的图片获取URL"接口获取，必填
     * @param string $author 作者
     * @param string $digest 图文消息的摘要，没有默认抓取正文前54个字
     * @param string $content_source_url 图文消息的原文地址，即点击“阅读原文”后的URL
     * @param mixed $need_open_comment 是否打开评论，默认：false
     * @param mixed $only_fans_can_comment 是否粉丝才可评论，默认：false
     * @return $this
     */
    public function addArticle($title, $thumb_media_id, $content, $author=null, $digest=null, $content_source_url=null, $need_open_comment=false, $only_fans_can_comment=false)
    {
        $row = [
            'title'=>$title,
            'thumb_media_id'=>$thumb_media_id,
            'content'=>$content,
            'need_open_comment'=>$need_open_comment ? 1 : 0,
            'only_fans_can_comment'=>$only_fans_can_comment ? 1 : 0,
        ];
        if ($author) $row['author'] = $author;
        if ($digest) $row['digest'] = $digest;
        if ($content_source_url) $row['content_source_url'] = $content_source_url;
        $this->articleList[] = $row;
        return $this;
    }

    /**创建图文草稿，需要先调用 addArticle 方法添加文章内容，调用完成后，会清空之前添加的文章
     * @return array 格式：['media_id'=>素材ID]
     * @throws SdkException
     */
    public function add()
    {
        self::assert(count($this->articleList), '图文列表为空，请先使用【addArticle】方法添加文章');
        $post_data = ['articles'=> $this->articleList];
        $res = $this->apiSdk('cgi-bin/draft/add', ['access_token'=>$this->accessToken()], json_encode($post_data,JSON_UNESCAPED_UNICODE));
        $this->articleList = [];
        return $res;
    }

    /**修改图文草稿，需要先调用 addArticle 方法添加文章内容，调用完成后，会清空之前添加的文章
     * @param string $media_id 素材ID
     * @param int $index 要更新的文章在图文消息中的位置，0序，默认：0
     * @return array
     * @throws SdkException
     */
    public function edit($media_id, $index=0)
    {
        self::assert(count($this->articleList), '图文列表为空，请先使用【addArticle】方法添加文章');
        $post_data = [
            'media_id'=> $media_id,
            'index'=> $index,
            'articles'=> $this->articleList[0],
        ];
        $res = $this->apiSdk('cgi-bin/draft/update', ['access_token'=>$this->accessToken()], json_encode($post_data,JSON_UNESCAPED_UNICODE));
        $this->articleList = [];
        return $res;
    }

    /**获取图文草稿列表
     * @param mixed $n 每页获取数量（1-20），默认：20
     * @param mixed $p 页码（0序），默认：0
     * @param mixed $need_content 是否获取content 字段
     * @return array 格式：['count'=>素材总数, 'list'=>[['media_id'=>'素材id','name'=>'素材名','update_time'=>'更新时间','url'=>'素材链接','news_item'=>'图文项目列表'],...]]
     * @throws SdkException
     */
    public function list($n=20, $p=0, $need_content=false)
    {
        self::assert($n<=20 && $n>0, '每页数量限制为1-20');
        $post_data = [
            'offset'=> $p*$n,
            'count'=> $n,
            'no_content'=> $need_content ? 0 : 1,
        ];
        $res = $this->apiSdk('cgi-bin/draft/batchget',['access_token'=>$this->accessToken()], json_encode($post_data, JSON_UNESCAPED_UNICODE));
        $list = $res['item'];
        foreach ($list as &$row){
            $news_item = $row['content']['news_item'];
            unset($row['content']);
            $row['news_item'] = $news_item;
            $row['name'] = $news_item[0]['title'];
            $row['url'] = $news_item[0]['url'];
        }
        return [
            'count'=> $res['total_count'],
            'list'=> $list,
        ];
    }

    /**图文草稿详情
     * @param string $media_id 素材id
     * @return array 格式：[['title','thumb_media_id','show_cover_pic','author','digest','content','url','content_source_url'],...]
     * @throws SdkException
     */
    public function info($media_id)
    {
        $post_data = ['media_id'=>$media_id];
        $res = $this->apiSdk('cgi-bin/draft/get',['access_token'=>$this->accessToken()], json_encode($post_data, JSON_UNESCAPED_UNICODE));
        if (is_array($res) && isset($res['news_item'])){
            return $res['news_item'];
        }
        return $res;
    }

    /**删除图文草稿
     * @param string $media_id 素材id
     * @return mixed
     * @throws SdkException
     */
    public function delete($media_id)
    {
        $post_data = ['media_id'=>$media_id];
        $res = $this->apiSdk('cgi-bin/draft/delete',['access_token'=>$this->accessToken()], json_encode($post_data, JSON_UNESCAPED_UNICODE));
        return $res;
    }

    /**发布图文草稿
     * @param string $media_id 素材id
     * @return array 格式：['publish_id'=>发布任务的id，用于查询发布结果,...]
     * @throws SdkException
     */
    public function publish($media_id)
    {
        $post_data = ['media_id'=>$media_id];
        $res = $this->apiSdk('cgi-bin/freepublish/submit',['access_token'=>$this->accessToken()], json_encode($post_data, JSON_UNESCAPED_UNICODE));
        return $res;
    }

    /**查询发布状态
     * @param string $publish_id 发布任务id
     * @return array 格式：['publish_id'=>发布任务id, 'article_id'=>图文的article_id, 'publish_status'=>发布状态, 'publish_status_str'=>发布状态说明, 'fail_idx'=>不通过的文章编号，1序]
     * @throws SdkException
     */
    public function publishStatus($publish_id)
    {
        $post_data = ['publish_id'=>$publish_id];
        $res = $this->apiSdk('cgi-bin/freepublish/get',['access_token'=>$this->accessToken()], json_encode($post_data, JSON_UNESCAPED_UNICODE));
        $publish_status_map = ['成功','发布中','原创失败','常规失败','平台审核不通过','成功后用户删除所有文章','成功后系统封禁所有文章'];
        $res['publish_status_str'] = $publish_status_map[$res['publish_status']] ?? '未知错误';
        if (empty($res['article_id'])) $res['article_id'] = '';
        return $res;
    }

    /**删除发布成功的图文
     * @param string $article_id 图文的article_id
     * @param int $index 文章编号，1序。传入0表示删除所有，默认：0
     * @return array
     * @throws SdkException
     */
    public function publishDelete($article_id, $index=0)
    {
        $post_data = ['article_id'=>$article_id];
        if ($index>0) $post_data['index'] = $index;
        $res = $this->apiSdk('cgi-bin/freepublish/delete',['access_token'=>$this->accessToken()], json_encode($post_data, JSON_UNESCAPED_UNICODE));
        return $res;
    }

    /**获取成功发布列表
     * @param mixed $n 每页获取数量（1-20），默认：20
     * @param mixed $p 页码（0序），默认：0
     * @param mixed $need_content 是否获取content 字段
     * @return array 格式：['count'=>素材总数, 'list'=>[['article_id'=>'图文的article_id','name'=>'文章标题','update_time'=>'更新时间','url'=>'素材链接','news_item'=>'图文项目列表'],...]]
     * @throws SdkException
     */
    public function publishList($n=20, $p=0, $need_content=false)
    {
        self::assert($n<=20 && $n>0, '每页数量限制为1-20');
        $post_data = [
            'offset'=> $p*$n,
            'count'=> $n,
            'no_content'=> $need_content ? 0 : 1,
        ];
        $res = $this->apiSdk('cgi-bin/freepublish/batchget',['access_token'=>$this->accessToken()], json_encode($post_data, JSON_UNESCAPED_UNICODE));
        $list = $res['item'];
        foreach ($list as &$row){
            $news_item = $row['content']['news_item'];
            unset($row['content']);
            $row['news_item'] = $news_item;
            $row['name'] = $news_item[0]['title'];
            $row['url'] = $news_item[0]['url'];
        }
        return [
            'count'=> $res['total_count'],
            'list'=> $list,
        ];
    }

    /**通过 article_id 获取已发布文章
     * @param string $media_id 素材id
     * @return array 格式：[['title','thumb_media_id','show_cover_pic','author','digest','content','url','content_source_url','is_deleted'],...]
     * @throws SdkException
     */
    public function publishInfo($article_id)
    {
        $post_data = ['article_id'=>$article_id];
        $res = $this->apiSdk('cgi-bin/freepublish/getarticle',['access_token'=>$this->accessToken()], json_encode($post_data, JSON_UNESCAPED_UNICODE));
        if (is_array($res) && isset($res['news_item'])){
            return $res['news_item'];
        }
        return $res;
    }

}